using System;
using umbraco;
using System.Reflection;
using System.Collections;

namespace Umbraco.Ecommerce.BusinessLogic.Automation
{
	public class ActionFactory
	{
		private static bool _handlersIsInitialized = false;
		private static ArrayList _actionHandlers = new ArrayList();
	
		private static void registerActionHandlers() 
		{
			string _pluginFolder = GlobalSettings.Path + "/../bin";
		
			foreach (string assembly in System.IO.Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(_pluginFolder), "*.dll")) 
			{
				try 
				{
					Assembly asm = System.Reflection.Assembly.LoadFrom(assembly);
					try 
					{
						foreach (Type t in asm.GetTypes()) 
						{
							Type hasInterface = t.GetInterface("store.BusinessLogic.Automation.IOrderActionHandler", true);

							if (hasInterface != null && !t.IsInterface) 
							{
								IOrderActionHandler typeInstance = Activator.CreateInstance(t) as IOrderActionHandler;
								_actionHandlers.Add(typeInstance);
							} 
						}
					} 
					catch {} // We all love empty catch blocks
				} 
				catch 
				{}  // Yet another one of the kind!
			}
			_handlersIsInitialized = true;
		}
	
		private static void print(string message) {
			System.Web.HttpContext.Current.Response.Write(message);
		}

		public static void RunActionHandlers(string Action, Order o) {
			if (!_handlersIsInitialized)
				registerActionHandlers();
		    foreach (IOrderActionHandler ioa in _actionHandlers) 
				ioa.HandleAction(Action,o);
			}
		}
	}
